﻿using Microsoft.AspNetCore.SignalR;

namespace SignalRServerDemo.Hubs
{
    public class LongTimePushHub : Hub<ILongTimePushClient>
    {
        private readonly ILogger<LongTimePushHub> _logger;

        public LongTimePushHub(ILogger<LongTimePushHub> logger)
        {
            _logger = logger;
        }

        public override Task OnConnectedAsync()
        {
            _logger.LogInformation($"建立连接，连接编号：{Context.ConnectionId} - {DateTime.Now}");
            return base.OnConnectedAsync();
        }

        public override Task OnDisconnectedAsync(Exception? exception)
        {
            if (exception != null)
            {
                _logger.LogError(exception, $"断开连接，连接编号：{Context?.ConnectionId} - {DateTime.Now}");
            }
            else
            {
                _logger.LogInformation($"断开连接，连接编号：{Context?.ConnectionId} - {DateTime.Now}");
            }

            return base.OnDisconnectedAsync(exception);
        }

        /// <summary>
        /// 加入组
        /// </summary>
        public Task JoinGroup(GroupData data)
        {
            _logger.LogInformation("加入组，接收数据：{0},{1}", data.id, data.groupId);
            return Groups.AddToGroupAsync(Context.ConnectionId, data.groupId);
        }

        /// <summary>
        /// 发送组消息
        /// </summary>
        public Task SendGroupMessage(GroupMessage message)
        {
            _logger.LogInformation("发送组消息，接收数据：{0},{1},{2}", message.id, message.groupId, message.message);
            return Clients.Groups(message.groupId).ClientHook(new TransPushData(message.id, message.message, DateTime.Now));
        }
    }

    public interface ILongTimePushClient
    {
        Task ClientHook(TransPushData data);
    }

    public record TransPushData(string id, string message, DateTime time);
}
